<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Task_list extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct() {
		parent::__construct();
		date_default_timezone_set('Asia/Shanghai'); 
		$this->load->library('pagination');
		ini_set('memory_limit', '3000M');
		$this->load->model('queue_model');//队列		
	}

	/**
	 * 用户登录
	 */
	public function login(){
		$this->load->view('login');
	}
	public function add_dd(){
        if (false == ($query = $this->db->query ( "SELECT * FROM `shijue_project_new` WHERE clue_type = 2 and status = 2 limit 10" ))) {
            echo "hot_word is null";
            return false;
        }
        
        $list = $query->result_array ();
        foreach ( $list as $word ) {

            $data = array();
            $data['task_id'] = $word['task_id'];
            $data['clue_id'] = $word['clue_id'];
            $data['company_id'] = $word['company_id'];
            $data['clue_address'] = $word['clue_address'];
            $this->queue_model->add_weixin_task ($data);
            $where = array(
			'id'=>$word['id']
			);
			$dd = array(
				'status'=>3
				);
			$r = $this->db->update('shijue_project_new', $dd, $where);

        }
        redirect('Task_list/index');

    }

	/**
	 * 用户登录
	 */
	public function login_post(){
		$this->load->library('session');
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$userData = $this->db->get_where('users',array('username'=>$username))->result_array();
		//检测用户名密码是否输入正确
		if(!$userData || $userData[0]['password'] != md5($password)){
			echo "<script>alert('用户名或密码错误请重新输入');window.history.back(-1);</script>" ;
		}else{
			$client_id=$userData[0]['id'];
			$sessionData = array(
				'c_id' =>$client_id,
				'username' =>$username,
				'logintime'=>time()
			);
			$rs = $this->session->set_userdata($sessionData);
			redirect('Task_list/index');
		}		
		
	}
	
	/**
	 * 退出用户中心
	 */
	public function logout(){
		session_destroy();
		redirect('Task_list/login');
	}


	public function test(){
		$url = "http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NTczNDAzMw==&amp;appmsgid=10000034&amp;itemidx=1&amp;sign=50df5588e09b739126ccd74dfa8210da&amp;scene=27#wechat_redirect";
		$rs = $this->send_http($url);
		print_r($rs);
	}

	public function index($page = 0)
	{
		#$this->output->enable_profiler();

		$this->session->data = array();

		$username = $this->session->userdata('username');
                if(!$username){
                        redirect('Task_list/login');
                }		
		$rs = $this->get_articlelist(array(), '', $page);
		//print_r($rs[1]);die;
		$data['list'] = $rs[1];
		$data['count'] = $rs[0];
		//==================================================
		  
		  //分页
		  $config = [
		   'base_url' => site_url().'/Task_list/index/',
		   'total_rows' => $data['count'],
		   'per_page' => 10,
		   'first_tag_open' => '<li>',
		   'first_tag_cloase' => '</li>',
		   'next_tag_open' => '<li>',
		   'next_tag_close' => '</li>',
		   'prev_tag_open' => '<li>',
		   'prev_tag_close' => '</li>',
		   'cur_tag_open' => '<li class="active"><a onclick="javascript:return false;">',
		   'cur_tag_close' => '</a ></li>',
		   'num_tag_open' => '<li>',
		   'num_tag_close' => '</li>',
		   'last_tag_open' => '<li>',
		   'last_tag_close' => '</li>',
		   'first_link' => '首页',
		   'last_link' => '尾页',
		   'reuse_query_string' => true,
		  ];

		  $this->pagination->initialize($config);

		  $data['article'] = $data['list'];
		  $data['clue'] = 'clue';
		  $data['username'] = $this->session->userdata('username');		  
		   

		//==================================================
		//var_dump($data['list']);die;
		$this->load->view('home',$data);
	}

	public function auto(){
		
		$_POST['clue_type']  = 1;
		$_POST['status'] = 3;

		$this->post_ser();
	}

	public function post_ser($page = 0){
		
		#$this->output->enable_profiler();

		$username = $this->session->userdata('username');
        if(!$username){
                redirect('Task_list/login');
        }
		//print_r($_POST);die;
		$data_post = array();
		if (!empty($_POST)) {
			if(isset($_POST['task_id'])){
				$data_post['task_id'] = $_POST['task_id'];
			}
			if(isset($_POST['clue_id'])){
				$data_post['clue_id']= $_POST['clue_id'];
			}
			if(isset($_POST['clue_type'])){
				$data_post['clue_type'] = $_POST['clue_type'];
			}
			if(isset($_POST['is_priority'])){
				$data_post['is_priority'] = $_POST['is_priority'];
			}
			if(isset($_POST['status'])){
				$data_post['status'] = $_POST['status'];
			}
			$this->session->data = $data_post;
		}
		
		//print_r($this->session->data);die;
		$rs = $this->get_articlelist($this->session->data, '', $page);
		//print_r($rs[1]);die;
		$data['list'] = $rs[1];
		$data['count'] = $rs[0];

		//==================================================
		  
		  //分页
		  $config = [
		   'base_url' => site_url().'/Task_list/post_ser/',
		   'total_rows' => $rs[0],
		   'per_page' => 10,
		   'first_tag_open' => '<li>',
		   'first_tag_cloase' => '</li>',
		   'next_tag_open' => '<li>',
		   'next_tag_close' => '</li>',
		   'prev_tag_open' => '<li>',
		   'prev_tag_close' => '</li>',
		   'cur_tag_open' => '<li class="active"><a onclick="javascript:return false;">',
		   'cur_tag_close' => '</a ></li>',
		   'num_tag_open' => '<li>',
		   'num_tag_close' => '</li>',
		   'last_tag_open' => '<li>',
		   'last_tag_close' => '</li>',
		   'first_link' => '首页',
		   'last_link' => '尾页',
		   'reuse_query_string' => true,
		  ];

		  $this->pagination->initialize($config);
		  $data['username'] = $this->session->userdata('username');
		  $data['article'] = $data['list'];
		  $data['clue'] = 'clue';
		   

		//==================================================
		//var_dump($data['list']);die;
		$this->load->view('home',$data);





	}

	public function export_excel(){
		if($this->session->data){
			$post = $this->session->data;

		}
		list($excel_count,$excel_data) = $this->get_excel_data($post);
		//print_r($excel_data);die;
		$rs = $this->sendexcel($excel_data);

	}
	public function get_clue($id = ''){
		$r = "select * FROM shijue_project_new where id = ".$id;
		$rs = $this->db->query($r);
		$data['clue_list'] = $rs->result_array();
		$this->load->view('tan',$data);

	}

	public function clue_status(){
		//print_r($_GET);die;
		$id = $_GET['id'];
		//$id = 5;
		$list_r = "select * FROM shijue_project_new where id =".$id;
		$sh = $this->db->query($list_r);
		$data = $sh->result_array();
		$update_clue = 'http://eagle.elephant.vcg.com/api/spider-update-clue';
				$clue_info = array(
					'task_id' => $data[0]['task_id'],
					'clue_id' => $data[0]['clue_id'],
					'status' => 3
					 );
		$clue_status = $this->send_post($update_clue,$clue_info);
		$where = array(
			'id'=>$id
			);
		$data = array(
			'status'=>4
			);
		$r = $this->db->update('shijue_project_new', $data, $where);
		if($r){
			echo 111;
		}
		

	}

	public function autospider(){
		//print_r($_GET);die;
		$id = $_GET['id'];
		//$id = 5;
		$list_r = "select * FROM shijue_project_new where id =".$id;
		$sh = $this->db->query($list_r);
		$data = $sh->row_array();
		
		// 加入队列让图片爬虫去抓数据
		$queue = array(
			'id' => $data['id'],
			'url' => $data['clue_address'],
			'clue_id' => $data['clue_id'],
			'task_id' => $data['task_id'],
			'company_id' => $data['company_id'],
			'clue_name' => $data['clue_name']
		);
		$this->queue_model->add_autospider($queue);

		// 标记子任务为处理中
		$where = array(
			'id'=>$id
		);
		$data = array(
			'status'=>3,
			'autospider'=>1
		);
		$r = $this->db->update('shijue_project_new', $data, $where);
		if($r){
			echo 111;
		}
		

	}


	public function get_articlelist($map = array(), $select = array(), $offset=0, $pagesize = 10, $order = null) {

		$map = array_filter($map);
		$out = $this->db->where($map)->get('shijue_project_new');
		#$c = $out->result_array();
		#$count = count($c);
		$count = $out->num_rows();
		$r = $this->db->select($select)->limit($pagesize)->where($map)->offset($offset)->order_by($order)->get('shijue_project_new');
		$rs = $r->result_array();

		foreach ($rs as $key => $value) {
			if($value['autospider'] == 1){
				// TODO 查询mongo中的总数
				$rs[$key]['count'] = $this->get_auto_count($value['clue_id']);

				// TODO 查询redis，判断是否抓取完成
				$rs[$key]['zcard'] = $this->get_auto_zcard($value['clue_id']);
			}
		}

		#echo "<pre>";print_r($rs);echo "</pre>";
		return array($count, $rs);
	}


	public function get_excel_data($map = array(), $select = array(), $offset=0, $pagesize = 200000, $order = null) {

		$map = array_filter($map);
		$out = $this->db->where($map)->get('shijue_project_new');
		$c = $out->result_array();
		$count = count($c);
		$r = $this->db->select($select)->limit($pagesize)->where($map)->offset($offset)->order_by($order)->get('shijue_project_new');
		$rs = $r->result_array();

		return array($count, $rs);
	}

	public function get_auto_count($clue_id){
		$this->config->load('mongodb');
		$mongo_config = $this->config->item('shijue_master');

		$this->load->library('Mongo_db', $mongo_config, 'shijue_master');
		
		$this->shijue_master->switch_db("auto");

		return $this->shijue_master->count("clue_id_".$clue_id);
	}

	public function get_auto_zcard($clue_id = "203067"){

		$this->load->model('cache_model');

		return $this->cache_model->zcard("clue_id_".$clue_id.":requests");
	}

	private function sendexcel($arrr){
       	

        //导入PHPExcel类库，PHPExcel没有用命名空间
        $this->load->library('PHPExcel');  //注意路径
        //创建PHPExcel对象
        $objPHPExcel=new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        //set width
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(28);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(28);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(28);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(200);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(14);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(14);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);
        //设置行高度
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);

        //set font size bold
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);

        $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

        //设置水平居中
        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB('#76EE00');
		$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB('#76EE00');
        $objPHPExcel->getActiveSheet()->getStyle('C1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('C1')->getFill()->getStartColor()->setARGB('#76EE00');
		$objPHPExcel->getActiveSheet()->getStyle('D1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('D1')->getFill()->getStartColor()->setARGB('#76EE00');
        //合并单元格,暂时不用
        //$objPHPExcel->getActiveSheet()->mergeCells('A1:H1');
        // set table header content
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '客户ID')
            ->setCellValue('B1', '主任务ID')
            ->setCellValue('C1', '子任务ID')
            ->setCellValue('D1', '网址')
            ->setCellValue('E1', 'uid')
            ->setCellValue('F1', '状态')
            ->setCellValue('G1', '')
            ->setCellValue('H1', '')
            ->setCellValue('I1', '')
            ->setCellValue('J1', '')
            ->setCellValue('K1', '')
            ->setCellValue('L1', '')
            ->setCellValue('M1', '')
            ->setCellValue('N1', '');

        foreach ($arrr as $k=>$v){
            $objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($k + 2), $v['company_id']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($k + 2), $v['task_id']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($k + 2), $v['clue_id']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('D' . ($k + 2), $v['clue_address']);
	    $objPHPExcel->getActiveSheet(0)->setCellValue('E' . ($k + 2), $v['biz']);
	    $objPHPExcel->getActiveSheet(0)->setCellValue('F' . ($k + 2), str_replace([2,4],['处理中','已完成'],$v['status']));
        }

        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle('tmp');

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
        // Redirect output to a client’s web browser (Excel5)
        ob_end_clean();//清除缓冲区,避免乱码

        //输出方式二:保存在服务器,然后返回保存文件名称
        $rs='shijue'.date('Y-m-d-H-i-s').'.xls';
	    header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition:attachment;filename=".$rs); 
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        //return $rs;

    }


	public function lvyou()
	{
		$this->load->view('test');
	}


	public function task_status(){
		//print_r($_GET);die;
		$id = $_GET['id'];
		//$id = 1;
		$list_r = "select * FROM shijue_project_new where task_id =".$id;
		$sh = $this->db->query($list_r);
		$data = $sh->row_array();

		$update_task = 'http://eagle.elephant.vcg.com/api/spider-update-task';
				$task_info = array(
					'task_id' => $data['task_id'],
					'status' => 4
					 );
		$task_status = $this->send_post($update_task,$task_info);
		if($task_status){
			$rr = json_decode($task_status,true);
               	        if($rr['status'] == '200'){
                        	$where = array(
                                	'task_id'=>$id
                        	);
                        	$data = array(
                                	'status_zong'=>3
                       		);
                        	$r = $this->db->update('shijue_project_new', $data, $where);
                        	echo 111;
                	}
			if($rr['status'] == '400'){
                        	$ss['msg'] = $rr['msg'];
                        	$rs = $this->db->insert('task_info',$ss);
                        	echo 222;
                	}
		}
		

	}



	public function post_task()
	{	$data['username'] = $this->session->userdata('username');	
		if(empty($_POST['task_id'])){
			echo "<script>alert('主任务ID不能为空。');</script>";
			redirect('Task_list/task');
		}
		$task_id = $_POST['task_id'];
		$query = "SELECT * FROM shijue_project_new where task_id =".$task_id;
		$res = $this->db->query($query);
		$data['list'] = $res->row_array();
		$data['list'] = array($data['list']);
		$data['task'] = 'task';
		//print_r(array($data['list']));die;
		$this->load->view('task',$data);
	}
	public function msg(){

	$query = "select * from task_info";
	$res = $this->db->query($query);
	$data['list'] = $res->result_array();
	$data['msg'] = 111;
	$data['username'] = $this->session->userdata('username');
	$this->load->view('msg',$data);


	


	}
	public function delete_msg($id){
	$query = "delete from task_info where id =".$id;
	$res = $this->db->query($query);
	if($res){
		echo "<script>alert('删除成功');window.history.back(-1);</script>";	
	}else{
		echo "<script>alert('删除失败');window.history.back(-1);</script>";	
	}
	


	}
	public function task($page = 0)
	{	

		$query = "SELECT DISTINCT(task_id),status_zong,is_priority,id FROM shijue_project_new where status_zong = 2 or status_zong = 3 GROUP BY task_id order by is_priority DESC,task_id limit {$page},10;";
		$res = $this->db->query($query);
		$data['list'] = $res->result_array();
		//print_r($data['list']);die;
		 $config = [
		   'base_url' => site_url().'/Task_list/task/',
		   'total_rows' => 1000,
		   'per_page' => 10,
		   'first_tag_open' => '<li>',
		   'first_tag_cloase' => '</li>',
		   'next_tag_open' => '<li>',
		   'next_tag_close' => '</li>',
		   'prev_tag_open' => '<li>',
		   'prev_tag_close' => '</li>',
		   'cur_tag_open' => '<li class="active"><a onclick="javascript:return false;">',
		   'cur_tag_close' => '</a ></li>',
		   'num_tag_open' => '<li>',
		   'num_tag_close' => '</li>',
		   'last_tag_open' => '<li>',
		   'last_tag_close' => '</li>',
		   'first_link' => '首页',
		   'last_link' => '尾页',
		   'reuse_query_string' => true,
		  ];

		  $this->pagination->initialize($config);

		  $data['article'] = $data['list'];
		  $data['task'] = 'task';
		  $data['username'] = $this->session->userdata('username');
		  $username = $this->session->userdata('username');
                	if(!$username){
                        	redirect('Task_list/login');
                	}
		$this->load->view('task',$data);
	}

	public function gj_data()
	{
		
		$data = $_POST['gj'];
		$pro_name = $_POST['pro_name'];
		$d = explode("\n",$data);
		//print_r($pro_name);die;
		foreach ($d as $v) {
			$data = array();
			$data['pro_name'] = $pro_name;
			$data['guanjian']=$v;
			$rs = $this->db->insert('hanergy_gj',$data);
			//print_r($v);die;
		}
		echo "<script>alert('添加成功.');</script>";
		$this->load->view('test');
		
	}

	public function qg_data()
	{
		
		$data = $_POST['qg'];
		$pro_name = $_POST['pro_name'];
		$d = explode("\n",$data);
		//print_r($pro_name);die;
		foreach ($d as $v) {
			$data = array();
			$data['pro_name'] = $pro_name;
			$data['qinggan']=$v;
			$rs = $this->db->insert('hanergy',$data);
			//print_r($v);die;
		}

		echo "<script>alert('添加成功.');</script>";
		$this->load->view('test');
		
	}

	public function pc_data()
	{
		
		$data = $_POST['pc'];
		$pro_name = $_POST['pro_name'];
		$d = explode("\n",$data);
		//print_r($pro_name);die;
		foreach ($d as $v) {
			$data = array();
			$data['pro_name'] = $pro_name;
			$data['paichu']=$v;
			$rs = $this->db->insert('hanergy_pc',$data);
			//print_r($v);die;
		}
		echo "<script>alert('添加成功.');</script>";
		$this->load->view('test');
		
	}

	public function dt_list($fl = 'jingqu')
	{	
		#print_r($fl);
		$res=$this->db->where('pro_name',$fl)->get('hanergy');
		//返回受影响行数
     	$data['qinggan'] = $res->result_array();
     	$r=$this->db->where('pro_name',$fl)->get('hanergy_gj');
		//返回受影响行数
     	$data['guanjian'] = $r->result_array();
     	$rs=$this->db->where('pro_name',$fl)->get('hanergy_pc');
		//返回受影响行数
     	$data['paichu'] = $rs->result_array();
		$this->load->view('test_1',$data);
	}



	public function delete_guanjian($id)
	{	
		
		$res = $this->db->delete('hanergy_gj',array('id'=>$id));
		if($res){
			echo "<script>alert('删除成功.');</script>";
			$this->dt_list();
		}
	}

	public function delete_qinggan($id)
	{	
		
		$res = $this->db->delete('hanergy',array('id'=>$id));
		if($res){
			echo "<script>alert('删除成功.');</script>";
			$this->dt_list();
		}
	}
	public function delete_paichu($id)
	{	
		
		$res = $this->db->delete('hanergy_pc',array('id'=>$id));
		if($res){
			echo "<script>alert('删除成功.');</script>";
			$this->dt_list();
		}
	}

	public function zhuaqu()
	{
		$this->load->view('test_2');
	}
	public function add_data($fl = 'jingqu'){
		$guan = $this->db->where('pro_name',$fl)->get('hanergy_gj');
		$guan = $guan->result_array();
		$qing = $this->db->where('pro_name',$fl)->get('hanergy');
		$qing = $qing->result_array();
		foreach ($guan as $guan_data) {
			foreach ($qing as $qing_data) {
				$word = $guan_data['guanjian']." ".$qing_data['qinggan'];
				$page = 1;
				print_r($word);die;
				echo "\n";
				echo "\n";
				echo "================================";
				while($page < 3){
					$rs_array = array('word'=>$word,'page'=>$page,'token'=>'70511fdff801aa937c4d5017a3273e12','platform'=>"sina");
					$rs = $this->queue_model->add_shijue_task($rs_array);
					$page ++;
					echo $rs_array;
					echo $page;
					echo "+++++++++++++++++++++++++++++++";
				}
			}
		}
    }

    public function excel($table='jingqu'){
    	$article_tabname = $table . "_" . date("Ymd");
		header("Content-type:text/html");
		header("Content-Disposition:attachment;filename=".$article_tabname.".xls");

		$this->config->load('mongodb');
		$mongo_config = $this->config->item('master');
		$this->load->library('Mongo_db', $mongo_config);

		$this->mongo_db->switch_db($this->dbname);

		$array= $this->mongo_db->limit(0,1000000)->offset(1)->get($article_tabname);
		$str="文章ID\t"."负面词组合\t"."文章内容\t"."发布时间\t"."粉丝数\t"."url\n";
		foreach($array as $val){
			$str.=$val['uid']."\t".$val['side_gl']."\t".$val['text']."\t".$val['ctime']."\t".$val['friends_count']."\t".$val['url']."\n";

		}
	        	echo mb_convert_encoding($str, "GBK");
	}

	public function demo(){
    	if(false == ($json_keyword = $this->queue_model->get_shijue_task())){		
			echo "get_shijue_task is null";
			sleep(10);
			return false;
		}
		$test = json_decode($json_keyword,true);
    	$url = "http://59.110.86.68:802/keyword/index";
    	$data = $this->send_http($url,$test);
    	$info = json_decode($data, TRUE);
    	if($info['data'] == false){
			$data = $this->send_http($url,$test);
			$info = json_decode($data, TRUE);
		}
	$this->load->config('side');
        $side_pai = $this->config->item('side_pai');
    	foreach ($info['data'] as $lists) {
    		//if( $this->today_time > $lists['ctime'] && $lists['ctime']> $this->yes_time){
    		if( time() > $lists['ctime'] && $lists['ctime']> 1498838400){
			$rs = array();
    			$rs['side_gl'] = $test['word'];
    			$rs['uid'] = $lists['_id'];
    			$rs['text'] = $lists['text'];
    			$rs['ctime'] =date("Y-m-d H:i:s",$lists['ctime']);
			$rs['friends_count']=$lists['user']['followers_count'];
			$rs['url'] = $lists['url'];
			foreach($side_pai as $pai){
			$b = strstr($rs['text'],$pai);
			if($b){
			      unset($rs);	
			}else{
			      echo "不存在排除词";
			}
			}
		    	$query = $this->mongo_db->get_where($this->article_tabname, array('text' =>$rs['text']));
		    	print_r($query);
				if(!$query){
					echo "++++++++++++++++++++++";
					$rs_data = $this->mongo_db->insert($this->article_tabname, $rs);
				}else{
					echo "======================";
					$side_data = array();
					$side_info = explode(" ", $test['word']);
					print_r($side_info);
					$re = strstr($query[0]['side_gl'],$side_info[1]);
					if($re == false){
						$side_data['side_gl'] = $query[0]['side_gl']." ".$side_info[1];
						print_r($side_data);
						$rs_data = $this->mongo_db->where(array('uid' =>$rs['uid']))->update($this->article_tabname, $side_data);
						var_dump($rs_data);
					}else{
						echo "已存在";
						exit;
					}
					
				}
		    }
    	}

    }



	public function yes_task()
	{
		$this->load->view('yes_task');
	}


	public function no_task()
	{
		$this->load->view('no_task');
	}


	public function home()
	{	

	
		$url = "http://v2.eagle.elephant.vcg.com/api/spider-tasks";
		$res = $this->get_url($url);
		$res_array = json_decode($res,true);
		//print_r($res_array);die;
		if (! empty ( $res_array['data'] ) && isset ( $res_array['data'] )) {
			$data = $res_array['data'];
		}else{
			return false;
		}
		foreach ($data as $v) {
			$task_info = array(
     				'task_id' => $v['task_id'],
     				'status' => 3
     			);
			$update_task = 'http://v2.eagle.elephant.vcg.com/api/spider-update-task';
			$task_status = $this->send_post($update_task,$task_info);
			//print_r($task_status);die;
			$list = $v['clues'];
			foreach ($list as $lists) {
				$clue_data = array();
				$clue_data['task_id']=$v['task_id'];
				$clue_data['company_id']=$v['company_id'];
				$clue_data['clue_id']=$lists['clue_id'];
				$clue_data['clue_address']=$lists['clue_address'];
				$clue_data['clue_type']=$lists['clue_type'];
				$clue_data['is_priority']=$v['is_priority'];
				
				$this->db->insert('shijue_project_new',$clue_data);
				$update_clue = 'http://v2.eagle.elephant.vcg.com/api/spider-update-clue';
				$clue_info = array(
					'task_id' => $v['task_id'],
					'clue_id' => $lists['clue_id'],
					'status' => 2
					 );
				$clue_status = $this->send_post($update_clue,$clue_info);

			

			}

		
			
		}
	

		redirect('Task_list/index');

		
	}
	public function send_post($url, $post_data = '', $timeout = 5){//curl  
        $ch = curl_init();  
        curl_setopt ($ch, CURLOPT_URL, $url);  
        curl_setopt ($ch, CURLOPT_POST, 1);  
        if($post_data != ''){  
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
        }  
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);   
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
        curl_setopt($ch, CURLOPT_HEADER, false);  
        $file_contents = curl_exec($ch);  
        curl_close($ch);  
        return $file_contents;  
    }  



	function get_url($url)   
	{  
	    $ch = curl_init();  
	    curl_setopt($ch, CURLOPT_URL,$url);  //设置访问的url地址     
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);      
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//不输出内容  
	    $result =  curl_exec($ch);  
	    curl_close ($ch);  
	    return $result;   
	}  

		function send_http($url, $post = array(), $ip = "", $timeout = 60, $header = array(), $connecttimeout = 60) {

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36');
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

		if($post){
			if(is_array($post)){
				$post = http_build_query($post);
			}
			echo $post;
			echo "\n";
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}

		if ($header){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		$rs = curl_exec($ch);
		$http_info = curl_getinfo($ch);
		
		curl_close($ch);
		if($http_info['http_code'] != 200 && $http_info['http_code'] != 302 ){
			return false;
		}
		return $rs;
	}

}
